﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DddCms.Presentation.MetaData;
using DddCms.Presentation.UIComponent.Grid;

namespace DddCms.Presentation.Utility
{
    public class HelperModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(
                                 IEnumerable<Attribute> attributes,
                                 Type containerType,
                                 Func<object> modelAccessor,
                                 Type modelType,
                                 string propertyName)
        {

            var data = base.CreateMetadata(
                                 attributes,
                                 containerType,
                                 modelAccessor,
                                 modelType,
                                 propertyName);

            if (attributes.Any(a => typeof(SortingAttribute) == a.GetType()))
            {
                data.AdditionalValues
                        .Add("Sorting", buildSortingViewModel(attributes));
                data.AdditionalValues
                        .Add("SortingName", propertyName);
            }

            return data;
        }

        private SortingViewModel buildSortingViewModel(IEnumerable<Attribute> attributes)
        {
            SortingViewModel item = new SortingViewModel();

            item.SortingItems = attributes
                .Where(a => typeof(SortingAttribute) == a.GetType())
                .ToList()
                .ConvertAll(c => (SortingAttribute)c)
                .Select(s => new SortingViewModel.SortingItem()
                {
                    Name = s.Name,
                    PropertyName = s.PropertySortName
                }).ToList();

            return item;
        }
        
    }
}